package cn.minsh.lims.eoms.modules.app.controller;

import cn.minsh.lims.eoms.common.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.xml.bind.annotation.adapters.CollapsedStringAdapter;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.UUID;

/**
 * @author Administrator
 */
@RestController
@RequestMapping("oss")
@Api(tags = "图片上传")
public class UploadController {

    @Value("${file.store.inPath}")
    private String fileStoreInpath ;
    @Value("${file.store.outPath}")
    private String fileStoreOutpath ;

    @PostMapping("/upload")
    @ApiOperation("图片上传")
    public R upload(@RequestParam("file") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            System.out.println("文件为空空");
        }
        String fileName = file.getOriginalFilename();
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        fileName = UUID.randomUUID() + suffixName;
        File dest = new File(fileStoreInpath + fileName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String filename = fileStoreOutpath + fileName;
        return R.ok().put("data", filename);
    }

    @PostMapping("/batchUpload")
    @ApiOperation("图片批量上传")
    public R batchUpload(@RequestParam("files") List<MultipartFile> files) throws Exception {
        List<String> retList = new ArrayList<>() ;
        if (CollectionUtils.isEmpty(files)) {
            System.out.println("文件不能为空");
            return R.error("文件为空") ;
        }
        files.forEach(file->{
            String fileName = file.getOriginalFilename();
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            fileName = UUID.randomUUID() + suffixName;
            File dest = new File(fileStoreInpath+ fileName);
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            try {
                file.transferTo(dest);
            } catch (IOException e) {
                e.printStackTrace();
            }
            String url = fileStoreOutpath + fileName;
            retList.add(url) ;
        });

        return R.ok().put("data", retList);
    }
}
